<!-- 登录注册 -->
<template>
    <div class="main-container">
        <div class="flex-box main-left">
            <h2 class="name">Away 博客管理系统</h2>
            <div class="img-content flx-center">
                <el-image class="el-image" :src="loginbg" fit="cover"></el-image>
            </div>
        </div>
        <div class="flex-box main-right flx-center">
            <div class="operate-center">
                <div class="form-container register-container" :class="activeControl ? 'register-container-active':''">
                    <div class="center-box flx-center" justify="center">
                        <h1>注册</h1>
                        <el-form :model="registerForm" size="large" ref="registerRef" :rules="rules">
                            <el-form-item label="" prop="userId">
                                <el-input v-model.trim="registerForm.userId" placeholder="用户名"></el-input>
                            </el-form-item>
                            <!-- <el-form-item label="" prop="phoneNumber">
                                <el-input v-model="registerForm.phoneNumber" placeholder="手机号"></el-input>
                            </el-form-item> -->
                            <el-form-item label="" prop="eMail">
                                <el-input v-model.trim="registerForm.eMail" placeholder="邮箱"></el-input>
                            </el-form-item>
                            <el-form-item label="" prop="password">
                                <el-input type="password" v-model.trim="registerForm.password"  placeholder="密码"></el-input>
                            </el-form-item>
                            <el-form-item label="" prop="verificationCode" class="code-item">
                                <el-input v-model.trim="registerForm.verificationCode" @keyup.enter="onRegister" placeholder="验证码">
                                    <template #append>
                                        <el-button type="" :disabled="codeDisabled" @click="onSendCode">{{emailCode}}</el-button>
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-form>
                        <el-button size="large" @click="onRegister" :loading="registerLoading">注册</el-button>
                    </div>
                </div>
                <div class="form-container login-container" :class="activeControl ? 'login-container-active':''">
                    <div class="center-box flx-center">
                        <h1>登录</h1>
                        <el-form :model="loginForm" size="large" ref="loginRef" :rules="rules">
                            <el-form-item label="" prop="userId">
                                <el-input v-model.trim="loginForm.userId" placeholder="用户名"></el-input>
                            </el-form-item>
                            <el-form-item label="" prop="password">
                                <el-input type="password" v-model.trim="loginForm.password" @keyup.enter="onLogin" placeholder="密码"></el-input>
                            </el-form-item>
                        </el-form>
                        <!-- <p @click="onUpdatePassword">忘了密码？</p> -->
                        <el-button size="large" @click="onLogin"  :loading="loginLoading">登录</el-button>
                    </div>
                </div>
                <div class="overlay-container" :class="activeControl ? 'overlay-container-active':''">
                    <div class="overlay-box" :class="activeControl ? 'overlay-box-active':''">
                        <div class="overlay-panel flx-center overlay-left" :class="activeControl ? 'overlay-left-active':''">
                            <h1>已有账号？</h1>
                            <p>请登录</p>
                            <button class="overlay-btn" @click="activeClick">登录</button>
                        </div>
                        <div class="overlay-panel flx-center overlay-right" :class="activeControl ? 'overlay-right-active':''">
                            <h1>没有账号？</h1>
                            <p>立即注册吧</p>
                            <button class="overlay-btn" @click="activeClick">注册</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import loginbg from '@/assets/images/login.png';
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store/system/user';
import { ElMessage } from 'element-plus';

import { usersApi } from '@/api/users/users/users-api';
import { loginApi } from '@/api/system/login/login-api';

import { USER_ROLE_NAME, USER_STATE } from '@/constants/system/user-const';
import { aes } from '@/utils/crypto-util';
import { PHONE_REGEXP, EMAIL_REGEXP } from '@/utils/verify-util';
import { countDown } from '@/utils/countdown-util';
import { COOKIE_TOKEN_KEY, saveTokenToCookie, } from '@/utils/cookie-util';

import { HOME_PAGE_PATH } from '@/constants/system/home-const';
import { SEND_EMAIL_TYPE } from '@/constants/system/email-const';
// ========================= 实列挂载之前调用 =========================
onBeforeMount(() => {

})

// ========================= 切换效果点击 =========================
let activeControl = ref(false);
function activeClick() {
    activeControl.value = !activeControl.value;
};

// ========================= 注册 =========================
// 注册表单控制
const rules = reactive({
    userId: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    eMail: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    verificationCode: [
        { required: true, message: '请输入验证码', trigger: 'change' }
    ],
});
// 注册表单
const registerForm = reactive({
    userId:'', // 用户名
    nickname:'', // 昵称
    avatar:'', // 头像
    phoneNumber:'', // 手机号码
    eMail:'', // 邮箱
    password:'', // 密码
    verificationCode:'', // 验证码
    state: USER_STATE.NORMAL.value, // 状态
    roles: USER_ROLE_NAME.ORDINARY_USER.value, // 角色
    createAt:'',
    updateAt:'',
})
const registerRef = ref();
let registerLoading = ref(false);

async function onRegister() {
    registerRef.value.validate(async (valid) => {
        try{
            if(valid) {
                registerLoading.value = true;
                let date = new Date();
                let form = {};
                form = {...form, ...registerForm};
                form.password = aes.en(form.password);
                form.createAt = date;
                form.updateAt = date;
                form.verificationCode = form.verificationCode.toUpperCase();
                const res = await usersApi.register(form);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                useUserStore().setUserInfo(res.data);
                ElMessage.success('注册成功');
            }
        } catch(e) {
            console.error(e);
            ElMessage.error(e.message);
        } finally {
            registerLoading.value = false;
        };
    });
};

// 发送验证码
let emailCode = ref('发送'); // 提示文字
let codeDisabled = ref(false); // 按钮控制
async function onSendCode() {
    try {
        if(!registerForm.eMail) {
            ElMessage.error('请输入邮箱');
            return false;
        };
        codeDisabled.value = true; // 发送按钮控制
        let countDownNum = 60;// 倒计时
        countDown(countDownNum, (dataNum) => {
            if(typeof dataNum == "object") {
                emailCode.value = '发送';
                codeDisabled.value = false;
                return;
            };
            emailCode.value = dataNum;
        });
        // 验证码接口
        const res = await loginApi.emailSend({
            sendType:SEND_EMAIL_TYPE.REGISTER.value, // 注册
            eMail:registerForm.eMail,
        });
        if(res.meta.status !== 200) throw new Error(res.meta.msg);
        ElMessage.success('发送成功');
    } catch (e) {
        console.error(e);
        ElMessage.error(e.message);
    }
};

// ========================= 登录 =========================
const loginRef = ref();
let loginLoading = ref(false);
const router = useRouter(); // 路由
// 登录表单
const loginForm = reactive({
    userId:'',
    password:''
})
// 登录
async function onLogin() {
    loginRef.value.validate(async (valid) => {
        try{
            if(valid) {
                loginLoading.value = true;
                let date = new Date();
                let form = {};
                form = {...form, ...loginForm};
                form.userId = aes.en(form.userId);
                form.password = aes.en(form.password);
                form.updateAt = date;
                const res = await loginApi.login(form);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                loginLoading.value = false;
                useUserStore().setUserInfo(res.data.data, res.data.token);
                ElMessage.success('登录成功');
                router.push(HOME_PAGE_PATH);
            }
        } catch(e) {
            console.error(e);
            ElMessage.error(e.message);
        } finally {
            loginLoading.value = false;
        }
    })
};

// ========================= 忘记密码 =========================
const updatePasswordRef = ref();
function onUpdatePassword() {
    updatePasswordRef.value.onShowPassword();
};

</script>

<style lang="scss" scoped>
    @import '@/theme/animations.scss';
    @import './login-register.scss';
</style>

